package com.novel.crawl.common.service.impl;

import com.novel.common.service.impl.BaseServiceImpl;
import com.novel.crawl.common.entity.Book;
import com.novel.crawl.common.entity.Recommendation;
import com.novel.crawl.common.service.BookService;
import com.novel.crawl.common.service.RecommendationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author 奔波儿灞
 * @since 1.0
 */
@Service
public class RecommendationServiceImpl extends BaseServiceImpl<Recommendation> implements RecommendationService {

    @Autowired
    private BookService bookService;

    @Override
    public Page<Recommendation> page(Recommendation recommendation, Pageable pageable) {
        Page<Recommendation> page = super.page(recommendation, pageable);
        List<Recommendation> recommendations = page.getContent();
        // 关联book到recommendation
        if (!CollectionUtils.isEmpty(recommendations)) {
            List<String> bookIds = recommendations.stream().map(Recommendation::getBookId).collect(Collectors.toList());
            Map<String, Book> bookMap = bookService.findByIds(bookIds).stream()
                    .collect(Collectors.toMap(Book::getId, book -> book));
            recommendations.forEach(re -> re.setBook(bookMap.get(re.getBookId())));
        }
        return page;
    }

}
